package web.dao.impls;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import map.beans.GeneralConfigBean;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import web.dao.interfaces.AdditionalConfigDao;

@Repository("additionalConfigDao")
@Transactional(readOnly = true)
public class AdditionalConfigDaoImpl implements AdditionalConfigDao {
	private static Logger LOGGER = LoggerFactory.getLogger(AdditionalConfigDaoImpl.class);
	private final int FIRST = 0;
	
	@PersistenceContext
	private EntityManager entityManager;

	@Override
	@Transactional
	public Long update(GeneralConfigBean genConfig) {
		try {
			System.out.println("........... Persisting Object  ..............");
			
			GeneralConfigBean gcb = getDefaultConfig();			
			genConfig.setId((gcb != null) ? gcb.getId() : null);
			
			entityManager.merge(genConfig);
			entityManager.flush();
		} catch (Exception e) {
			LOGGER.error(e.getMessage());
		}
		return genConfig.getId();
	}

	@Override
	public GeneralConfigBean getDefaultConfig() {		
		return findAll().isEmpty() ? null : findAll().get(FIRST);
	}
	
	@Override
	public List<GeneralConfigBean> findAll() {
		TypedQuery<GeneralConfigBean> query = entityManager.createQuery("SELECT g FROM GeneralConfigBean g ORDER BY g.id", GeneralConfigBean.class);
		return query.getResultList();
	}
	
	
	@Override
	public void delete(GeneralConfigBean config) {
		// check that it exists in the DB
		config = entityManager.getReference(GeneralConfigBean.class, config.getId());
		
		if (config != null) {					
			entityManager.remove(config);
			entityManager.flush();
		}
	}
}
